package com.mano.mall.web.shop.member.controller;

import com.alibaba.fastjson.JSONObject;
import com.mano.commons.web.utils.RandomValidateCodeUtil;
import com.mano.mall.api.dto.member.input.UserInputDTO;
import com.mano.mall.common.base.BaseResponse;
import com.mano.mall.common.constants.Constants;
import com.mano.mall.common.utils.MyBeanUtils;
import com.mano.commons.web.base.BaseWebController;
import com.mano.mall.web.shop.member.feign.MemberRegisterServiceFeign;
import com.mano.mall.web.shop.member.req.vo.RegisterVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
@Slf4j
public class RegisterController extends BaseWebController {

	private static final String MB_REGISTER_FTL = "member/register";
	private static final String MEMBER_REGISTER_PAGE = "member/register";
	private static final String MB_LOGIN_FTL = "member/login";


	@Autowired
	private MemberRegisterServiceFeign memberRegisterServiceFeign;

	/**
	 * 跳转到注册页面
	 * 
	 * @return
	 */
	@GetMapping("/register")
	public String getRegister() {
		return MEMBER_REGISTER_PAGE;
	}

	/**
	 * 跳转到注册页面
	 * 
	 * @return
	 */
	@PostMapping("/register")
	public String postRegister(@ModelAttribute("registerVo") @Validated RegisterVo registerVo, BindingResult bindingResult, HttpSession httpSession, Model model) {

		// 1.参数验证
		if (bindingResult.hasErrors()) {
			// 获取第一个错误!
			String errorMsg = bindingResult.getFieldError().getDefaultMessage();
			setErrorMsg(model, errorMsg);
			return MB_REGISTER_FTL;
		}

		// 2.图形验证码验证
		String graphCOde = registerVo.getGraphicCode();
		// 这样会出现分布式session 问题哦 ，需要处理分布式
		Boolean checkVerify = RandomValidateCodeUtil.checkVerify(graphCOde, httpSession);
		if(!checkVerify){
			setErrorMsg(model, "图形验证码失败");
			return MB_REGISTER_FTL;
		}

		// 将VO转换DTO
		UserInputDTO inputDTO = MyBeanUtils.doToDto(registerVo, UserInputDTO.class);

		try{
			String registCode = registerVo.getRegistCode();
			BaseResponse<JSONObject> register = memberRegisterServiceFeign.register(inputDTO, registCode);
			if (!register.getCode().equals(Constants.HTTP_RES_CODE_200)) {
				model.addAttribute("error", register.getMsg());
				return MB_REGISTER_FTL;
			}

		}catch (Exception e){
			log.error(">>>>>", e);
			model.addAttribute("error", "系统出现错误!");
			return MB_REGISTER_FTL;

		}

		// 注册成功,跳转到登陆页面
		return MB_LOGIN_FTL;


	}

}
